<?php

namespace App\Http\Controllers\Api;

use App\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;

class TokenController extends Controller
{
   /***
    * JWT 获取token
    */
   public function auth(Request $request)
   {
      //获取用户信息

      //生成token
      $user = User::first();
      $token = JWTAuth::fromUser($user);
      return response()->json(compact('token'));
   }

   /***
    *  获取openid
    */
   public function get_openid()
   {
      $client = new Client();  //获取远程接口
      $app_id = config('pay.wechat.app_id');
      $redirect_uri = urlencode('https://********/api/pay/wechat_mp');  //授权后重定向的回调链接地址
      $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$app_id&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
//      $result = https_curl($url, 'get', 'json');  //一种方法
      $response = $client->get($url);  //二种方法
      $result = json_decode($response->getBody(), true);  //转为数组
      $code = $result['code'];  //获取code
      $secret = config('pay.wechat.key');
      $data = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$app_id&secret=$secret&code=$code&grant_type=authorization_code";
//      $res = https_curl($data, 'get', 'json');
      $http = $client->get($data);
      $res = json_decode($http->getBody(), true);
      $openid = $res['openid'];

      return $openid;
   }
}
